package com.example.cet4try.Utils;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

import com.example.cet4try.AssetsDatabaseManager;
import com.example.cet4try.activity.ActivityDatabaseManager;

import java.util.ArrayList;
import java.util.Random;

public class Tools {
    public static WordData souEN(String en){
//        String[] table = {"english","chinese","phonetic","mark","example"};//+mode_id
//        String[] res = new String[table.length+1];
        en = "'"+en+"'";
        WordData wordData = null;

        SQLiteDatabase mydb = getDB();
        Cursor c = mydb.rawQuery("SELECT * FROM cet4word WHERE english="+en,null);

        if (c.moveToFirst()){
            /*for (int i=0;i<table.length;i++){
                res[i] = c.getString(c.getColumnIndex(table[i]));
            }*/
            wordData = DB2WordData(c);
        }
        else{
            c.close();
            return null;
        }
//        res[5] = "4_"+c.getString(c.getColumnIndex("_id"));

        c.close();
        return wordData;
    }

    public static WordData souID(int id){
//        String[] table = {"english","chinese","phonetic","mark","example"};//+mode_id
//        String[] res = new String[table.length+1];
        WordData wordData = new WordData();

        SQLiteDatabase mydb = getDB();
        Cursor c = mydb.rawQuery("SELECT * FROM cet4word WHERE _id=?", new String[]{Integer.toString(id)});

        if(c.moveToFirst()){
            /*for (int i=0;i<table.length;i++){
                res[i] = c.getString(c.getColumnIndex(table[i]));
            }*/
            wordData = DB2WordData(c);
        }
        else{
            c.close();
            return wordData;
        }

        c.close();
        return wordData;
    }

    public static void getAllWordData(String table,ArrayList<String> data){
        SQLiteDatabase mydb = getDB();
        Cursor c = mydb.rawQuery("SELECT * FROM "+table, null);
        //data.add("id");data.add("english");data.add("chinese");data.add("phonetic");data.add("example");
        String[] columnsName = new String[]{"_id","english","chinese","phonetic","example"};
        while (c.moveToNext()){
            for (String s : columnsName) {
                data.add(c.getString(c.getColumnIndex(s)));
            }
        }
        c.close();

    }

    private static WordData DB2WordData(Cursor c){
        WordData wordData = new WordData();
        wordData.setMode("4");//"english","chinese","phonetic","mark","example"
        wordData.setId(c.getString(c.getColumnIndex("_id")));
        wordData.setEnglish(c.getString(c.getColumnIndex("english")));
        wordData.setChinese(c.getString(c.getColumnIndex("chinese")));
        wordData.setPhonetic(c.getString(c.getColumnIndex("phonetic")));
        wordData.setExample(c.getString(c.getColumnIndex("example")));
        return wordData;
    }

    public static boolean SQLiteExecSQL(String sql){
        SQLiteDatabase mydb = getDB();
        try {
            mydb.execSQL(sql);
        }
        catch (SQLException e){
            return false;
        }
        return true;
    }

    public static boolean SQLiteupdateData(String table, String set,String where){
        String sql = "UPDATE "+table+" SET "+set+" "+where;

        return SQLiteExecSQL(sql);
    }

    private static final String DB_FALSE = "0";
    private static final String DB_TRUE = "1";

    public static void CreateUserData(String username){
        String sql ="CREATE TABLE data_"+username+" ( " +
                "id TEXT, " +
                "learned TEXT, " +  //已学
                "already TEXT, " +  //已会
                "wrong TEXT, " +    //错题
                "collect TEXT " +   //收藏
                ");";

        SQLiteExecSQL(sql);
    }

    public static void AddUserData(String username,String s_id,String type){
        SQLiteDatabase mydb = getDB();
        ContentValues values = new ContentValues();
        values.put(type,DB_TRUE);
        if (CheckUserData(username,s_id,null) == 1){
            mydb.update("data_"+username, values, "id = ?", new String[]{s_id});
        }
        else {
            values.put("id",s_id);
            mydb.insert("data_"+username,null,values);
        }
    }

    public static void DelUserData(String username,String s_id,String type){
        SQLiteDatabase mydb = getDB();
        ContentValues values = new ContentValues();
        values.put(type, DB_FALSE);
        mydb.update("data_"+username, values, "id = ?", new String[]{s_id});
    }

    public static int CheckUserData(String username,String s_id,String type){
        SQLiteDatabase mydb = getDB();
        String data_user = "data_"+username;
        Cursor c = null;
        try {
            c = mydb.rawQuery("SELECT * FROM "+data_user+" WHERE id=?", new String[]{s_id});
        }
        catch (SQLException e){
            CreateUserData(username);
            return -1;
        }
        if (c.moveToNext()){
            if (type == null)
                return 1;
            String flag = c.getString(c.getColumnIndex(type));
            if (flag != null)
                if (flag.equals("1"))
                    return 1;
        }
        return 0;
    }

    public static ArrayList<WordClass> GetRemainDBData(String username){
        return GetDBData(GetUserDatasEnglish(username,"learned"));
    }

    public static ArrayList<WordClass> GetDBData(){
        return GetDBData(null);
    }

    public static ArrayList<WordClass> GetDBData(ArrayList<String> learnedList){
        SQLiteDatabase mydb = getDB();
        Cursor c = mydb.rawQuery("SELECT * FROM cet4word",null);
        ArrayList<WordClass> mList = new ArrayList<WordClass>();
        while (c.moveToNext()){
            String english = c.getString(c.getColumnIndex("english"));
            String chinese = c.getString(c.getColumnIndex("chinese"));
            WordClass wordClass = new WordClass(english,chinese);
            boolean b = true;
            if (learnedList != null){
                b = !learnedList.contains(english);
            }
            if (b)
                mList.add(wordClass);
        }
        return mList;
    }

    public static ArrayList<WordClass> GetUserDatas(String username,String type){
        SQLiteDatabase mydb = getDB();
        String data_user = "data_"+username;
        Cursor c = mydb.rawQuery("SELECT * FROM "+data_user+" WHERE "+type+"=1",null);
        ArrayList<String> collectList = new ArrayList<String>();
        while(c.moveToNext()){
            String temp = c.getString(c.getColumnIndex("id"));
            collectList.add(temp);
        }
        //"english","chinese","phonetic","mark","example"
        ArrayList<WordClass> collectList2 = new ArrayList<WordClass>();
        for (int i = 0;i<collectList.size();i++){
            String[] temps = collectList.get(i).split("_");
            WordData wordData = souID(Integer.parseInt(temps[1]));
//            collects[i] = ;
//            collectList2.add(data[0]+"_"+data[1]);
            collectList2.add(new WordClass(wordData.getEnglish(),wordData.getChinese()));
        }

        return collectList2;

    }

    public static ArrayList<String> GetUserDatasEnglish(String username,String type){
        SQLiteDatabase mydb = getDB();
        String data_user = "data_"+username;
        Cursor c = mydb.rawQuery("SELECT * FROM "+data_user+" WHERE "+type+"=1",null);
        ArrayList<String> collectList = new ArrayList<String>();
        while(c.moveToNext()){
            String temp = c.getString(c.getColumnIndex("id"));
            collectList.add(temp);
        }
        //"english","chinese","phonetic","mark","example"
        ArrayList<String> collectList2 = new ArrayList<String>();
        for (int i = 0;i<collectList.size();i++){
            String[] temps = collectList.get(i).split("_");
            WordData wordData = souID(Integer.parseInt(temps[1]));
//            collects[i] = ;
//            collectList2.add(data[0]+"_"+data[1]);
            collectList2.add(wordData.getEnglish());
        }

        return collectList2;

    }

    public static int CountUserData(String username,String type){
        SQLiteDatabase mydb = getDB();
        String data_user = "data_"+username;
        Cursor c = null;
        try {
            c = mydb.rawQuery("SELECT COUNT(*) FROM "+data_user+" WHERE "+type+"=1",null);
        }
        catch (SQLException e){
            return 0;
        }
        if (c.moveToNext()){
            return c.getInt(0);
        }
        return 0;

    }

    private static SQLiteDatabase getDB(){
        AssetsDatabaseManager mg = AssetsDatabaseManager.getManager();
        SQLiteDatabase db = mg.getDatabase("myDB.db");

        return db;
    }

    public static void DBupdate(String english, String value){
        SQLiteDatabase mydb = getDB();

        ContentValues values2 = new ContentValues();
        values2.put("mark", value);
        mydb.update("cet4word", values2, "english = ?", new String[]{english});

    }

    public static int MyRandom(int min,int max){
        if (min == max)
            return min;
        Random random = new Random();
        return random.nextInt(max)%(max-min+1) + min;
    }

    public static String GetRandomdata(String data){
        String[] rt = null;
        rt = data.split("#");
        int r = 0;
        if (rt.length>1)
           r = MyRandom(0,rt.length-1);

        return rt[r];
    }

    public static String Readdata(String data){
        String[] rt = null;
        rt = data.split("#");
        int r = 0;

        return rt[r];
    }

    public static String getChinese(String string){
        String[] strs = string.split("#");
        StringBuilder stringBuilder = new StringBuilder();
        for (String str : strs) {
            String temp = str + "\n";
            stringBuilder.append(temp);
        }
        string = stringBuilder.toString();
        return string;
    }

    public static String getYinbiao(String string){
        String[] strs = string.split("#");
        StringBuilder stringBuilder = new StringBuilder();
        for (String str : strs) {
            String temp = "[" + str + "]  ";
            stringBuilder.append(temp);
        }
        string = stringBuilder.toString();
        return string;
    }

    public static  String gseLizi(String english,String string){
        String font_start = "<font color='#909090'>";
        String font_end = "</font>";
        String[] strs = string.split("#");
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i<strs.length; i++){
            String temp;
            if (i%2==0){
                String t = strs[i];
                String[] ts = t.split("^\\d\\.+|\\s|\\.$|,|\\?|!");
                for (int k = 1;k < ts.length;k ++){
                    String tt = ts[k].toLowerCase();
                    String en = english.toLowerCase();

                    if (en.length() > 1){
                        if (en.substring(en.length()-1).contains("e"))
                            en = en.substring(0,english.length()-1);
                    }

                    if (tt.indexOf(en) == 0){
                        /*if (en.length() <= 3 && tt.length() != en.length()){
                            continue;
                        }*/
                        t = t.replaceAll(ts[k],"<font color='#497BFB'>"+ts[k]+font_end);
                    }

                }
                /*if (t.contains(" "+english))
                    t = "<font color='#497BFB'>" + t + font_end;*/
                temp = t + "<br>";
            }
            else {
                temp = font_start + strs[i] + font_end + "<br><br>";
            }
            stringBuilder.append(temp);
        }
        string = stringBuilder.toString();

        return string;
    }

    public static int dp2px(Context context, float dp){
        float scale = context.getResources().getDisplayMetrics().density;
        return (int)(dp*scale+0.5f);
    }

}
